const { ccclass, property } = cc._decorator;

import AudioManager from "./AudioManager";
import AbTestMgr from "./AbTestMgr";
import PeripheralSystemDataMgr from "./PeripheralSystemDataMgr";
import EventMgr from "./EventMgr";
import GameEventType from "./GameEventType";
import EngineUtil from "./EngineUtil";
import BasePageCtrl, { AnimType } from "./BasePageCtrl";
import PeripheralSystemMgr from "./PeripheralSystemMgr";
import UiManage from "./UiManage";
import NoviceFundrewardPage from "./NoviceFundrewardPage";
import FundRewardBoxItemCtrl from "./FundRewardBoxItemCtrl";

@ccclass
export default class NoviceFundrewardPageCtrl extends BasePageCtrl {
@property(cc.Prefab)
boxItemPrefab: cc.Prefab = null;

private otherBoxArr: FundRewardBoxItemCtrl[] = [];
private selectNode: cc.Node = null;

onLoad() {
    this.onUILoad();
    this._animType = AnimType.SCALE;
    this._touchControl = false;
    this._hasPeneLock = true;
    this._hasBlack = true;
    this._hasTouchLock = false;
    this._hasBlackTouch = false;
    this._reuse = false;
    super.onLoad();
    this.addButtonListen();
    this.addEvent();
}

addEvent() {
    EventMgr.listen(GameEventType.SHOW_GUIDE_FUND_REWARD, this.showReward, this);
    EventMgr.listen(GameEventType.FUND_BOX_OPEN_DONE, this.playRewardAction, this);
}

start() {}

_init() {
    this.addReward();
}

showReward() {
    const rewardList = ["8元", "18元", "28元", "38元", "58元", "78元", "88元", "98元"];
    let selectNode = null;
    this.ui.boxNode.children.forEach((node: cc.Node) => {
        const boxItem = node.getComponent(FundRewardBoxItemCtrl);
        boxItem.setCanClick(false);
        boxItem.closeSchedule();
        if (boxItem.haveSelect) {
            boxItem.setLightShow(true);
            selectNode = node;
        } else {
            this.otherBoxArr.push(boxItem);
            boxItem.setLightShow(false);
        }
    });

    const shuffledList = EngineUtil.shuffleArr2(rewardList);
    for (let i = 0; i < this.otherBoxArr.length; i++) {
        const reward = shuffledList[i];
        const boxItem = this.otherBoxArr[i];
        boxItem.playBoxSpine("idle2", true);
        boxItem.setRewardFund(reward);
    }

    this.selectNode = selectNode;
}

playRewardAction() {
    this.ui.boxNode.getComponent(cc.Layout).type = cc.Layout.Type.NONE;

    this.otherBoxArr.forEach((boxItem: FundRewardBoxItemCtrl) => {
        boxItem.changeRewardSp(false);
        boxItem.setBoxShow(false);
    });

    this.scheduleOnce(() => {
        const selectNode = this.selectNode;

        this.otherBoxArr.forEach((boxItem: FundRewardBoxItemCtrl) => {
            boxItem.node.active = false;
        });

        this.ui.receive_title.active = true;
        this.ui.receive_title.opacity = 0;
        cc.tween(this.ui.receive_title).to(1, { opacity: 255 }).start();
        this.ui.reward_title.active = false;

        const finalCashNode = this.ui.finalCashNode;
        const position = selectNode.getPosition();
        const finalPosition = this.calculationDis(position, finalCashNode.getPosition()) <= 20
            ? position
            : finalCashNode.parent.convertToNodeSpaceAR(selectNode.getParent().convertToWorldSpaceAR(position));

        cc.tween(selectNode)
            .to(1, { position: finalPosition })
            .call(() => {
                this._playTextAnimation();
            })
            .start();
    }, 2.8);
}

calculationDis(pos1: cc.Vec2, pos2: cc.Vec2): number {
    const dx = pos1.x - pos2.x;
    const dy = pos1.y - pos2.y;
    return Math.sqrt(dx * dx + dy * dy);
}

addReward() {
    return new Promise<void>((resolve) => {
        this.ui.boxNode.removeAllChildren();

        cc.loader.loadRes("FundRewardBoxItem", cc.Prefab, (err, prefab) => {
            if (err) {
                console.error(err);
                return;
            }

            for (let i = 0; i < 9; i++) {
                const boxItem = cc.instantiate(prefab).getComponent(FundRewardBoxItemCtrl);
                boxItem.initData({ index: i });
                this.ui.boxNode.addChild(boxItem.node);
                this.otherBoxArr.push(boxItem);
            }

            resolve();
        });
    });
}

onUILoad() {
    this.ui = this.node.addComponent(NoviceFundrewardPage);
}

addButtonListen() {
    UiManage.addButtonListen(this.ui.btn_revice, this.clickRevice, this, 0);
}

clickRevice() {
    if (PeripheralSystemDataMgr.getOutsideGuideStep() !== PeripheralSystemMgr.OutSideLevelGuide.FUND_PROVICE) {
        this.hide();
        PeripheralSystemDataMgr.setOutsideStep(PeripheralSystemMgr.OutSideLevelGuide.FUND_PROVICE);
        PeripheralSystemMgr.reportOutsideGuideStep(PeripheralSystemMgr.OutSideLevelGuide.FUND_PROVICE);
    }
}

clickClose() {
    this.hide();
}

onBlackTouch() {
    if (PeripheralSystemDataMgr.getOutsideGuideStep() !== PeripheralSystemMgr.OutSideLevelGuide.FUND_PROVICE) {
        super.onBlackTouch();
        PeripheralSystemDataMgr.setOutsideStep(PeripheralSystemMgr.OutSideLevelGuide.FUND_PROVICE);
        PeripheralSystemMgr.reportOutsideGuideStep(PeripheralSystemMgr.OutSideLevelGuide.FUND_PROVICE);
    }
}

onDestroy() {
    EventMgr.ignore(GameEventType.SHOW_GUIDE_FUND_REWARD, this.showReward, this);
    EventMgr.ignore(GameEventType.FUND_BOX_OPEN_DONE, this.playRewardAction, this);
}
}
NoviceFundrewardPageCtrl.prefabUrl = "NoviceFundrewardPage";
NoviceFundrewardPageCtrl.className = "NoviceFundrewardPageCtrl";